const koa = require('koa');
const app = new koa();

function sleep(ts) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, ts);
  });
}

app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*');
  if (ctx.url === '/test') {
    await sleep(200);
    const n = Math.random();

    // 随机挂掉接口
    if (n > 0.8) {
      ctx.body = n;
    } else {
      ctx.status = 404;
      ctx.body = '';
    }
    next();
  }
});

app.listen(3000, () => {
  console.log('listening on at port 3000');
});
